/**
 * 定义分页全局变量
 */
var page_ = new page({pageSize:50,search:search,callback:func});

/**
 * 定义容器全局变量
 */
var con = new container({
	datagrid:'#datagrid',
	//datagridtoolbar:'#datagrid-toolbar',
	singleSelect:true,pagination:false});

$(function(){
	/**
	 * 获取列表页面（行为）按钮
	 */
	var authCondition = {
			//userId:$("#index #userId").val(),
			menuCode:curMenu.code,
			drawerCode:行为类型_前端组件,
			authAreaCode:授权分类_角色管理_列表,
			callback:action,
			con:"#datagrid-toolbar"}
	findResourcesByUserId(authCondition);
	
	$("#grant").tabs({
		border:false,
	    onSelect:function(title,index){
	    	if(index == 0){
	    		resource()
	    	}else if(index == 1){
	    		organ();
	    	}
	    },
	    tools:'#datagrid-toolbar'
	});
	search(page_);
});

/**
 * 回调函数
 */
function func(){
	$("#datagrid").datagrid({onClickRow:function(index,row){
		
		findMenusById(row);
		findResourcesById(row);

		var organTree = $.fn.zTree.getZTreeObj("organTree");
		if(organTree){
			organTree.checkAllNodes(false);
		}
		
		initSuccessCallBack();
	}});
}

function initSuccessCallBack(data){
	setCheck();
	$("#setting #py").bind("click", setCheck);
	$("#setting #sy").bind("click", setCheck);
	$("#setting #pn").bind("click", setCheck);
	$("#setting #sn").bind("click", setCheck);
	var row = $("#datagrid").datagrid('getSelected');
	if(row){
		$.ajax({
			type : "GET",
			url : ctx + "/role/findOrganById",
			data :{id : row.id},
			dataType : "json",
			success : function(data) {
				if(!showMsg(data)){
					return;
				}
				var tree = $.fn.zTree.getZTreeObj("organTree");
				if(tree){
					for(var i=0;i<data.content.length;i++){
						$("#organIds").append("<input type='hidden' name='" + data.content[i].id + "' value='" + data.content[i].id + "'>");
						var node = tree.getNodeByParam("id", data.content[i].id);
						if(node != null)
							tree.checkNode(node, true, false);
					}
				}
			}
		});
	}
}

/**
 * 异步加载成功后，回调函数，用于初始化已被绑定的机构
 * @param data
 */
function onAsyncSuccessAfterCallBack(data){
	var tree = $.fn.zTree.getZTreeObj("organTree");
	for(var i=0;i<data.length;i++){
		if($("input[type=hidden][name='"+data[i].id+"']").length != 0)
			tree.checkNode(data[i], true, false);
	}
}

/**
 * 查询
 * @param page
 */
function search(pg){
	var url = ctx + "/role/query";
	page_.pageSize = pg.pageSize;
	page_.pageNumber = pg.pageNumber;
	query(url, getCondition(), con, page_);
}

/**
 * 获取查询条件
 * @returns {condition}
 */
function getCondition(){
	
	var condition = {};
	
	condition.organId = $("#index #organId").val();
	
	return condition;
}

/**
 * 添加
 */
function add(){
	$('#dialog').dialog({
	    title: '添加',
	    width: 360,
	    height: 205,
	    closed: false,
	    cache: false,
	    modal: true,
	    href:ctx + "/web/system/role/add.jsp",
	    onClose:function(){
	    	destroy('dialog','#dialogDiv');
	    },
	    onLoad:function(){
	    	$("#addform").form('load',{});
	    },
	    buttons: [{
            text:'保存',
            iconCls:'icon-ok',
            handler:function(){
            	var bool = $("#addform").form('enableValidation').form('validate');
            	if(!bool){
            		return;
            	}
            	var name = $("#name").textbox("getValue");
            	
            	var data = {};
            	data.name = name;
            	data.organId= $("#index #organId").val();
            	
            	$.ajax({
            		type : "POST",
            		url : ctx + "/role/create",
            		data :data,
            		dataType : "json",
            		success : function(data) {
            			if(!showMsg(data,"添加成功")){
            				return;
            			}
            			
            			search(page_);
            			
            			$('#dialog').dialog('close');
            		}
            	});
            }
        },{
            text:'取消',
            iconCls:'icon-cancel',
            handler:function(){
            	$('#dialog').dialog('close');
            }
        }]
	});
}

/**
 * 修改
 */
function edit(){
	var row = null;
	row = getSelectedRow("#datagrid");
	if(!row){
		return;
	}
	$('#dialog').dialog({
	    title: '修改',
	    width: 360,
	    height: 205,
	    closed: false,
	    cache: false,
	    modal: true,
	    href:ctx + "/web/system/role/add.jsp",
	    onClose:function(){
	    	destroy('dialog','#dialogDiv');
	    },
	    onLoad:function(){
	    	$("#name").textbox("setValue",row.name);
	    },
	    buttons: [{
            text:'保存',
            iconCls:'icon-ok',
            handler:function(){
            	var bool = $("#addform").form('enableValidation').form('validate');
            	if(!bool){
            		return;
            	}
            	var name = $("#name").textbox("getValue");
            	var data = {};
            	data.id = row.id;
            	data.name = name;
            	
            	$.ajax({
            		type : "POST",
            		url : ctx + "/role/update",
            		data :data,
            		dataType : "json",
            		success : function(data) {
            			if(!showMsg(data,"修改成功")){
            				return;
            			}
            			
            			search(page_);
            			
            			$('#dialog').dialog('close');
            		}
            	});
            }
        },{
            text:'取消',
            iconCls:'icon-cancel',
            handler:function(){
            	$('#dialog').dialog('close');
            }
        }]
	});
}

/**
 * 删除
 */
function del(){
	var row = null;
	row = getSelectedRow("#datagrid");
	if(!row){
		return;
	}
	
	$.messager.confirm('提示', '确定要删除吗?', function(bool){
	    if (bool){
	    	$.ajax({
	    		type : "POST",
	    		url : ctx + "/role/delete",
	    		data :{id : row.id},
	    		dataType : "json",
	    		success : function(data) {
	    			if(!showMsg(data,"删除成功")){
        				return;
        			}
	    			
	    			search(page_);
	    		}
	    	});
	    }
	});
}

/**
 * 初始化资源
 */
function resource(){
	var resource_tab = $('#grant').tabs('getTab','资源授权');  // get selected panel
	$('#grant').tabs('update',{tab:resource_tab,options:{
		title: resource_tab.panel('options').title,
	    border:false,
	    fit:true,
	    href:ctx + "/web/system/role/bind.jsp",
	    onLoad:function(){
	    	$.ajax({
	    		type : "GET",
	    		url : ctx + "/tree/menu",
	    		data :{id : $("#index #userId").val()},
	    		dataType : "json",
	    		success : function(data) {
	    			if(!showMsg(data)){
        				return;
        			}
	    			
	    	    	var setting = {
	    	    			check: {
	    	    				enable: true
	    	    			},
	    	    			data: {
	    	    				simpleData: {
	    	    					enable: true,
	    	    					pIdKey: "pid",
	    	    				},
	    	    				key:{
	    	    					name:'name'
	    	    				}
	    	    			},
	    	    			callback: {
	    	    				onCheck: mTreeOnCheck,
	    	    				beforeCheck: mTreeBeforeCheck
	    	    			}
	    	    		};
	    	    	
	    	    	$.fn.zTree.init($("#mtree"), setting, data.content);
	    	    	var row = $("#datagrid").datagrid('getSelected');
	    	    	if(row)
	    	    		findMenusById(row);
	    		}
	    	});
	    	
	    	$.ajax({
	    		type : "GET",
	    		url : ctx + "/tree/resource",
	    		data :{id : $("#index #userId").val()},
	    		dataType : "json",
	    		success : function(data) {
	    			if(!showMsg(data)){
        				return;
        			}
	    			
	    	    	var setting = {
	    	    			check: {
	    	    				enable: true
	    	    			},
	    	    			data: {
	    	    				simpleData: {
	    	    					enable: true,
	    	    					pIdKey: "pid",
	    	    				},
	    	    				key:{
	    	    					name:'name'
	    	    				}
	    	    			}
	    	    		};
	    	    	
	    	    	$.fn.zTree.init($("#rtree"), setting, data.content);
	    	    	var row = $("#datagrid").datagrid('getSelected');
	    	    	if(row)
	    	    		findResourcesById(row);
	    		}
	    	});
	    }
	}});
}

/**
 * 复选框选中事件
 */
function mTreeOnCheck(event, treeId, treeNode){
	var mtree = $.fn.zTree.getZTreeObj("mtree");
	mtree.selectNode(treeNode);
	var rtree = $.fn.zTree.getZTreeObj("rtree");
	var nodes = rtree.getNodesByFilter(filter_);
	for(var i = 0;i<nodes.length;i++){
		rtree.checkNode(nodes[i], treeNode.checked, true, false);
	}
}

/**
 * 复选框选中之前事件
 */
function mTreeBeforeCheck(treeId, treeNode){
	var row = null;
	row = getSelectedRow("#datagrid","请选中角色记录");
	if(!row){
		return false;
	}
}

function filter_(node) {
	var mtree = $.fn.zTree.getZTreeObj("mtree");
	var nodes = mtree.getSelectedNodes();
	if(nodes[0].code.length == 1){
		return node;
	}else if(nodes[0].code.length == 3){
		return (node.code.substring(0,3) == nodes[0].code);
	}else if(nodes[0].code.length == 6){
		return (node.code.substring(0,6) == nodes[0].code);
	}else if(nodes[0].code.length == 9){
		return (node.code.substring(0,9) == nodes[0].code);
	}else{
		return;
	}
}

/**
 * 绑定资源
 */
function bindResource(){
	var resource_tab = $('#grant').tabs('getSelected');
	if(resource_tab.panel('options').title != '资源授权'){
		message("请先选中资源授权tab页");
		return;
	}
	var row = null;
	row = getSelectedRow("#datagrid","请选中角色");
	if(!row){
		return;
	}
	var mtree = $.fn.zTree.getZTreeObj("mtree");
	var nodes = mtree.getCheckedNodes(true);	
	var index=0;
	$("#bindform").empty();
	$("#bindform").append("<input type='hidden' name='id' value='"+row.id+"'>");
    for(var i=0; i<nodes.length; i++){
        $("#bindform").append("<input type='hidden' name='menus["+index+"].id' value='"+nodes[i].id+"'>");
        index++;
    }
    var rtree = $.fn.zTree.getZTreeObj("rtree");
    nodes = rtree.getCheckedNodes(true);
    index=0;
    for(var i=0; i<nodes.length; i++){
    	var temp = mtree.getNodesByParam("id", nodes[i].id, null);
    	if(temp != null && temp.length !=0){
    		continue;
    	}
        $("#bindform").append("<input type='hidden' name='resources["+index+"].id' value='"+nodes[i].id+"'>");
        index++;
    }
    
    var data = $("#bindform").serializeJson();
    
	$('#bindform').form({
		url:ctx+"/role/bind",
		success: function(data){
			data = JSON.parse(data);
			if(!showMsg(data,'绑定成功')){
				return;
			}
	    }
    });
	$("#bindform").submit();
}

/**
 * 初始化机构
 */
function organ(){
	var organ_tab = $('#grant').tabs('getTab','机构授权');  // get selected panel
	$('#grant').tabs('update',{tab:organ_tab,options:{
		title: organ_tab.panel('options').title,
	    border:false,
	    fit:true,
	    href:ctx + "/web/system/role/bindorgan.jsp",
	    onLoad:function(){
	    	setting.check.enable = true;
	    	$("#expandAllBtn").bind('click',function(){
	    		expandAll();
	    	});
	    	$("#resetBtn").bind('click',function(){
	    		reset();
	    	});
	    }
	}});
}

/**
 * 绑定机构
 */
function bindOrgan(){
	var organ_tab = $('#grant').tabs('getSelected');
	if(organ_tab.panel('options').title != '机构授权'){
		message("请先选中机构授权tab页");
		return;
	}
	var row = null;
	row = getSelectedRow("#datagrid","请选中角色");
	if(!row){
		return;
	}
	var tree = $.fn.zTree.getZTreeObj("organTree");
	var nodes = tree.getCheckedNodes(true);	
	var index=0;
	$("#bindorganform").empty();
	$("#bindorganform").append("<input type='hidden' name='id' value='"+row.id+"'>");
    for(var i=0; i<nodes.length; i++){
		$("#bindorganform").append("<input type='hidden' name='organs["+index+"].id' value='"+nodes[i].id+"'>");
        index++;
    }
    
    var data = $("#bindorganform").serializeJson();
    
    $.ajax({
		type : "GET",
		url : ctx + "/role/bindOrgan",
		data :data,
		dataType : "json",
		success : function(data) {
			if(!showMsg(data,"绑定成功")){
				return;
			}
		}
	});
}


function setCheck() {
	var zTree = $.fn.zTree.getZTreeObj("organTree");
	if(!zTree){
		return;
	}
	var py = $("#py").is(':checked') ? "p":"",
	sy = $("#sy").is(':checked') ? "s":"",
	pn = $("#pn").is(':checked') ? "p":"",
	sn = $("#sn").is(':checked') ? "s":"",
	type = { "Y":py + sy, "N":pn + sn};
	zTree.setting.check.chkboxType = type;
}

/**
 * 获取选中角色绑定的菜单
 */
function findMenusById(row){
	$.ajax({
		type : "GET",
		url : ctx + "/role/findMenusById",
		data :{id : row.id},
		dataType : "json",
		cache:false,
		success : function(data) {
			if(!showMsg(data)){
				return;
			}
			var mtree = $.fn.zTree.getZTreeObj("mtree");
			if(mtree != null){
				mtree.checkAllNodes(false);
				for(var i=0;i<data.content.length;i++){
    				var node = mtree.getNodeByParam("id", data.content[i].id);
    				mtree.checkNode(node, true, false);
    			}
			}
		}
	});
}

/**
 * 获取选中角色绑定的资源
 */
function findResourcesById(row){
	$.ajax({
		type : "GET",
		url : ctx + "/role/findResourcesById",
		data :{id : row.id},
		dataType : "json",
		cache:false,
		success : function(data) {
			if(!showMsg(data)){
				return;
			}
			var rtree = $.fn.zTree.getZTreeObj("rtree");
			if(rtree){
				rtree.checkAllNodes(false);
				for(var i=0;i<data.content.length;i++){
    				var node = rtree.getNodeByParam("id", data.content[i].id);
    				rtree.checkNode(node, true, true);
    			}
/*    			
    			var node = rtree.getNodeByParam("id", '9999');
    			if(!node.checked)
    				rtree.checkNode(node, true, true);*/
			}
		}
	});
}